package com.hk.demo.player.http;

import com.hk.player.core.DataCallback;
import com.zhoug.common.content.Optional;
import com.zhoug.common.framework.rxjava2.SchedulerUtils;
import com.zhoug.common.utils.LogUtils;
import com.zhoug.common.utils.StringUtils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.disposables.Disposable;

/**
 * @author: zhoug
 * @since: 2025-06-20
 */
public class ApiRepository {
    private static final String TAG = ">>>ApiRepository";
    private static List<Disposable> mCache = new ArrayList<>();


    public ApiRepository() {
    }

    public Disposable login(String name, String pwd, String imageCode, String validSerialNumber, boolean UseCode, @NonNull DataCallback<LoginAccount> callback) {

        LinkedHashMap<String, Object> params = new RequestParamsBuild()
                .put(RequestParamsBuild.PARAMS.LoginName, name)
                .put(RequestParamsBuild.PARAMS.Password, pwd)
                .put(RequestParamsBuild.PARAMS.ValidCode, imageCode)
                .put(RequestParamsBuild.PARAMS.ValidSerialNumber, validSerialNumber)
                .put(RequestParamsBuild.PARAMS.LoginMode, UseCode)
                .build();
        Disposable disposable = HttpClient.getInstance().getBaseRequests().login(params)
                .subscribeOn(SchedulerUtils.io())
                .compose(ResponseTransformer.handleResult())
                .observeOn(SchedulerUtils.io())
                .map(loginResponseOptional -> {
                    LoginAccount loginAccount = loginResponseOptional.get();

                    return loginResponseOptional;
                })
                .observeOn(SchedulerUtils.ui())
                .subscribe(s -> callback.onSuccess(s.get()), throwable -> callback.onFailure(throwable.getMessage()));
        return disposable;
    }

    public Disposable getPreviewMonitorList(int pageIndex, int pageSize, DataCallback<List<FirmMonitor>> callback) {
     /*   LinkedHashMap<String, Object> params = new RequestParamsBuild()
                .putAreaCode(areaCode)
                .putFirmTypeCode(firmTypeCode)
                .putSearchName(searchName)
                .putTimes(startTime,endTime)
                .putPage(pageIndex,pageSize)
                .build();
        return BaseHttpClient.getInstance().getBaseRequests().getPreviewMonitorList(params)
                .compose(ResponseTransformer.handleResult());*/

        return Observable
                .create((ObservableOnSubscribe<Optional<List<FirmMonitor>>>) emitter -> {
                    List<FirmMonitor> firmMonitors = new ArrayList<>();
                    if(pageIndex>1){
                        emitter.onNext(Optional.create(firmMonitors));
                        emitter.onComplete();
                        return;
                    }
                    /*FirmMonitor  firmMonitor=new FirmMonitor();
                    firmMonitor.setFirmId("4726716492549842775");
                    firmMonitor.setFirmName("五一药店");
                    firmMonitor.setId("4783831662643273670");
                    firmMonitor.setName("桂中大药房五一药店1");
                    firmMonitor.setPlayUrl("4da874ced2ab461c82bb5d7aad796e2e");
                    firmMonitors.add(firmMonitor);

                     firmMonitor=new FirmMonitor();
                    firmMonitor.setFirmId("4726716492549842775");
                    firmMonitor.setFirmName("五一药店");
                    firmMonitor.setId("5567735942238034779");
                    firmMonitor.setName("桂中大药房五一药店2");
                    firmMonitor.setPlayUrl("02c02d14d7424834862781d22f796e26");
                    firmMonitors.add(firmMonitor);

                    firmMonitor=new FirmMonitor();
                    firmMonitor.setFirmId("4726716492549842775");
                    firmMonitor.setFirmName("五一药店");
                    firmMonitor.setId("5499424416691299094");
                    firmMonitor.setName("桂中大药房五一药店3");
                    firmMonitor.setPlayUrl("bd692247775a46188c744cb2902a0e35");
                    firmMonitors.add(firmMonitor);

                    firmMonitor=new FirmMonitor();
                    firmMonitor.setFirmId("4726716492549842775");
                    firmMonitor.setFirmName("五一药店");
                    firmMonitor.setId("5481978226113910033");
                    firmMonitor.setName("桂中大药房五一药店4");
                    firmMonitor.setPlayUrl("5a80e10119c94b6bbe8e3b4d3c7856bf");
                    firmMonitors.add(firmMonitor);

                    firmMonitor=new FirmMonitor();
                    firmMonitor.setFirmId("4726716492549842775");
                    firmMonitor.setFirmName("五一药店");
                    firmMonitor.setId("4957209587087662773");
                    firmMonitor.setName("桂中大药房五一药店5");
                    firmMonitor.setPlayUrl("665409fec29745139a9084378adf3358");
                    firmMonitors.add(firmMonitor);

                    firmMonitor=new FirmMonitor();
                    firmMonitor.setFirmId("4726716492549842775");
                    firmMonitor.setFirmName("五一药店");
                    firmMonitor.setId("5053573314334008332");
                    firmMonitor.setName("桂中大药房五一药店6");
                    firmMonitor.setPlayUrl("c97cde0623e94ea98cb0ff80bf3e9083");
                    firmMonitors.add(firmMonitor);*/

                    //南宁
                    FirmMonitor firmMonitor = new FirmMonitor();
                    firmMonitor.setFirmId("4718517443080488497");
                    firmMonitor.setFirmName("广西骨伤医院食堂");
                    firmMonitor.setId("4792047646733448016");
                    firmMonitor.setName("广西骨伤医院食堂_烹饪区_1");
                    firmMonitor.setPlayUrl("sgGHPh4AB1GJNQV6OG7H1D");
                    firmMonitors.add(firmMonitor);

                    firmMonitor = new FirmMonitor();
                    firmMonitor.setFirmId("4718517443080488497");
                    firmMonitor.setFirmName("广西骨伤医院食堂");
                    firmMonitor.setId("4991026485903691136");
                    firmMonitor.setName("广西骨伤医院食堂_切配区_1");
                    firmMonitor.setPlayUrl("sgGHPh4AB1GJNQV6OH61NT");
                    firmMonitors.add(firmMonitor);

                    firmMonitor = new FirmMonitor();
                    firmMonitor.setFirmId("4718517443080488497");
                    firmMonitor.setFirmName("广西骨伤医院食堂");
                    firmMonitor.setId("5003358395371009512");
                    firmMonitor.setName("广西骨伤医院食堂_洗消区_1");
                    firmMonitor.setPlayUrl("sgGHPh4AB1GJNQV6OG7GQK");
                    firmMonitors.add(firmMonitor);

                    firmMonitor = new FirmMonitor();
                    firmMonitor.setFirmId("5041725410365920173");
                    firmMonitor.setFirmName("南宁师范大学（建政校区）食堂");
                    firmMonitor.setId("4928836785980077036");
                    firmMonitor.setName("南宁师范大学（建政校区）食堂_配餐区_1");
                    firmMonitor.setPlayUrl("rz5vtslsA1GHUO8I7N4AS5");
                    firmMonitors.add(firmMonitor);

                    firmMonitor = new FirmMonitor();
                    firmMonitor.setFirmId("5041725410365920173");
                    firmMonitor.setFirmName("南宁师范大学（建政校区）食堂");
                    firmMonitor.setId("5353743658470566369");
                    firmMonitor.setName("南宁师范大学（建政校区）食堂_切配区_1");
                    firmMonitor.setPlayUrl("rz5vtslsA1GHUO8I7N4ABA");
                    firmMonitors.add(firmMonitor);

                    firmMonitor = new FirmMonitor();
                    firmMonitor.setFirmId("5041725410365920173");
                    firmMonitor.setFirmName("南宁师范大学（建政校区）食堂");
                    firmMonitor.setId("5510344856729490128");
                    firmMonitor.setName("南宁师范大学（建政校区）食堂_烹饪区_1");
                    firmMonitor.setPlayUrl("rz5vtslsA1GHUO8I7N4ANU");
                    firmMonitors.add(firmMonitor);

                    firmMonitor = new FirmMonitor();
                    firmMonitor.setFirmId("5041725410365920173");
                    firmMonitor.setFirmName("南宁师范大学（建政校区）食堂");
                    firmMonitor.setId("5540342088992132809");
                    firmMonitor.setName("南宁师范大学（建政校区）食堂_洗消区2_1");
                    firmMonitor.setPlayUrl("rz5vtslsA1GHUO8I7O2RL2");
                    firmMonitors.add(firmMonitor);

                    firmMonitor = new FirmMonitor();
                    firmMonitor.setFirmId("5041725410365920173");
                    firmMonitor.setFirmName("南宁师范大学（建政校区）食堂");
                    firmMonitor.setId("5656631706074753404");
                    firmMonitor.setName("南宁师范大学（建政校区）食堂_洗消区_1");
                    firmMonitor.setPlayUrl("rz5vtslsA1GHUO8I7N4A5K");
                    firmMonitors.add(firmMonitor);

                    firmMonitor = new FirmMonitor();
                    firmMonitor.setFirmId("11111");
                    firmMonitor.setFirmName("占位");
                    firmMonitor.setId("占位");
                    firmMonitor.setName("占位");
                    firmMonitor.setPlayUrl("占位");
                    firmMonitors.add(firmMonitor);

                    firmMonitor = new FirmMonitor();
                    firmMonitor.setFirmId("11111");
                    firmMonitor.setFirmName("占位");
                    firmMonitor.setId("占位");
                    firmMonitor.setName("占位");
                    firmMonitor.setPlayUrl("占位");
                    firmMonitors.add(firmMonitor);

                    firmMonitor = new FirmMonitor();
                    firmMonitor.setFirmId("11111");
                    firmMonitor.setFirmName("占位");
                    firmMonitor.setId("占位");
                    firmMonitor.setName("占位");
                    firmMonitor.setPlayUrl("占位");
                    firmMonitors.add(firmMonitor);

                    firmMonitor = new FirmMonitor();
                    firmMonitor.setFirmId("11111");
                    firmMonitor.setFirmName("占位");
                    firmMonitor.setId("占位");
                    firmMonitor.setName("占位");
                    firmMonitor.setPlayUrl("占位");
                    firmMonitors.add(firmMonitor);

                    firmMonitor = new FirmMonitor();
                    firmMonitor.setFirmId("11111");
                    firmMonitor.setFirmName("占位");
                    firmMonitor.setId("占位");
                    firmMonitor.setName("占位");
                    firmMonitor.setPlayUrl("占位");
                    firmMonitors.add(firmMonitor);

                    firmMonitor = new FirmMonitor();
                    firmMonitor.setFirmId("11111");
                    firmMonitor.setFirmName("占位");
                    firmMonitor.setId("占位");
                    firmMonitor.setName("占位");
                    firmMonitor.setPlayUrl("占位");
                    firmMonitors.add(firmMonitor);

                    firmMonitor = new FirmMonitor();
                    firmMonitor.setFirmId("11111");
                    firmMonitor.setFirmName("占位");
                    firmMonitor.setId("占位");
                    firmMonitor.setName("占位");
                    firmMonitor.setPlayUrl("占位");
                    firmMonitors.add(firmMonitor);

                    emitter.onNext(Optional.create(firmMonitors));
                    emitter.onComplete();
                })
                .compose(SchedulerUtils.apply())
                .subscribe(opt -> {
                    callback.onSuccess(opt.get());
                }, throwable -> {
                    callback.onFailure(throwable.getMessage());
                });


    }

    public Disposable getFirmMonitorPlayUrlById(String monitorId, int Protocol, DataCallback<String> callback) {
        LinkedHashMap<String, Object> params = new RequestParamsBuild()
                .withId(monitorId)
                .put("Protocol", Protocol)
//                .put("Clarity", clarity > 0 ? clarity : null)
                .build();
        Disposable disposable = HttpClient.handler(HttpClient.getInstance().getBaseRequests().getFirmMonitorPlayUrlById(params))
                .observeOn(SchedulerUtils.io())
                .map(s -> {
                    FirmMonitor firmMonitor = s.get();
                    if (firmMonitor != null && firmMonitor.getPlayUrl() != null) {
                        String playUrl = firmMonitor.getPlayUrl();
                        if (MyPlayUrlUtil.isPlayUrl(playUrl)) {
                            return Optional.create(playUrl);
                        } else if (StringUtils.isNullOrEmpty(playUrl)) {
                            throw new Exception("播放地址为空");
                        } else {
                            throw new Exception("播放地址格式不正确:" + playUrl);
                        }
                    } else {
                        String error = firmMonitor == null ? "firmMonitor is null" : "PlayUrl is null";
                        LogUtils.e(TAG, "获取摄像头地址失败:" + error);
                        throw new Exception(error);
                    }


                })
                .observeOn(SchedulerUtils.ui())
                .subscribe(s -> {
                    if (callback != null) {
                        callback.onSuccess(s.get());
                    }
                }, throwable -> {
                    if (callback != null) {
                        callback.onFailure(throwable.getMessage());
                    }
                });
        return disposable;

    }


    public Disposable getFirmMonitorPlayUrlByPlayUrl(String macUrl, int Protocol, DataCallback<String> callback) {
        LinkedHashMap<String, Object> params = new RequestParamsBuild()
                .put("PlayUrl", macUrl)
                .put("Protocol", Protocol)
//                .put("Clarity", clarity > 0 ? clarity : null)
                .build();
        Disposable disposable = HttpClient.handler(HttpClient.getInstance().getBaseRequests().getFirmMonitorPlayUrlByPlayUrl(params))
                .observeOn(SchedulerUtils.io())
                .map(s -> {
                    FirmMonitor firmMonitor = s.get();
                    if (firmMonitor != null && firmMonitor.getPlayUrl() != null) {
                        String playUrl = firmMonitor.getPlayUrl();
                        if (MyPlayUrlUtil.isPlayUrl(playUrl)) {
                            return Optional.create(playUrl);
                        } else if (StringUtils.isNullOrEmpty(playUrl)) {
                            throw new Exception("播放地址为空");
                        } else {
                            throw new Exception("播放地址格式不正确:" + playUrl);
                        }
                    } else {
                        String error = firmMonitor == null ? "firmMonitor is null" : "PlayUrl is null";
                        LogUtils.e(TAG, "获取摄像头地址失败:" + error);
                        throw new Exception(error);
                    }


                })
                .observeOn(SchedulerUtils.ui())
                .subscribe(s -> {
                    if (callback != null) {
                        callback.onSuccess(s.get());
                    }
                }, throwable -> {
                    if (callback != null) {
                        callback.onFailure(throwable.getMessage());
                    }
                });
        return disposable;

    }


    public void setLifecycleOwner(LifecycleOwner owner) {
        if (owner != null) {
            owner.getLifecycle().addObserver(new DefaultLifecycleObserver() {
                @Override
                public void onDestroy(@NonNull LifecycleOwner owner) {
                    disposable();
                }
            });
        }
    }

    private void addDisposable(Disposable disposable) {
        if (disposable != null && !disposable.isDisposed()) {
            mCache.add(disposable);
        }
    }


    public void disposable() {
        for (Disposable item : mCache) {
            if (item != null && !item.isDisposed()) {
                item.dispose();
            }
        }
        mCache.clear();
    }

}
